import React, { Component } from 'react'
import QueueAnim from 'rc-queue-anim'
import * as XLSX from 'xlsx'
import { connect } from 'react-redux'
import { AddShop } from './AddShop'
import { Button, Image, Space, Table, Tooltip, ConfigProvider, Empty, message, Drawer } from 'antd'
import { requestAddShopList } from '../../api/shop'

class AddQuit extends Component {
    state = {
        editVisible: false,
        edit: true,
        editRow: {},
        tableHeight: window.innerHeight - 340,
        dataSource: []
    }

    importExcel () {
        const input = document.createElement('input')
        const fileReader = new FileReader()
        const isExcel = /\.xls|\.xlsx$/
        input.type = 'file'
        input.click()
        input.onchange = () => {
            const { name: filename } = input.files[0]
            if (isExcel.test(filename)) {
                message.success('检测到excel文件')
                fileReader.readAsBinaryString(input.files[0])
                fileReader.onload = () => {
                    const workbook = XLSX.read(fileReader.result, { type: 'binary' })
                    const sheet = workbook.Sheets['sheet']
                    const records = XLSX.utils.sheet_to_json(sheet)
                    records.forEach(item => {
                        item.swiper = item.swiper.split(',')
                    })
                    this.setState({
                        dataSource: this.state.dataSource.concat(records)
                    })
                }
            } else {
                message.error('这个文件不是excel文件')
                console.log('不是excel')
            }
        }
    }

    edit (proname) {
        let item = this.state.dataSource.find(item => item.proname === proname)
        item = {
            ...item, swiper: item.swiper.map((item, index) => {
                return {
                    thumbUrl: item,
                    name: 'picture' + (index + 1)
                }
            })
        }
        this.setState({
            editRow: item,
            edit: true,
            editVisible: true
        })
    }

    remove (values) {
        const dataSource = this.state.dataSource
        const Index=this.findIndex(values)
        dataSource.splice(Index,1)
        this.setState({
            dataSource:[...dataSource]
        })
    }

    appendRow (values, fromRef) {
        this.setState({
            dataSource: this.state.dataSource.concat([values]),
            editVisible: false
        })
        setTimeout(() => {
            fromRef.current.resetFields()
        }, 1000)
    }

    modifyRow (values, formRef) {
        if (!values) {
            return
        }
        let index = 0
        let { dataSource } = this.state
        index = this.findIndex(values)
        dataSource[index] = values
        this.setState({
            dataSource: [...dataSource],
            editVisible: false
        }, () => {
            formRef.current.resetFields()
        })
    }

    findIndex (values) {
        let index = 0
        for (let item of this.state.dataSource) {
            if (item.proname === values.proname) {
                return index
            }
            index++
        }
        return index
    }

    addShopList () {
        this.setState({
            edit: false,
            editVisible: true
        })
    }

    uploadShopList () {
        console.log('上传商品')
        const { dataSource } = this.state
        const uploadAll = []
        if (!dataSource.length) {
            message.warn('上传队列为空')
            return
        }
        dataSource.forEach(item => {
            const upload = requestAddShopList(item)
            uploadAll.push(upload)
        })
        Promise.all(uploadAll).then(res => {
            message.success('全部上传成功')
            this.setState({
                dataSource: []
            })
        })
    }

    handerEditVisible () {
        this.setState({
            editVisible: false
        })
    }

    render () {
        const columns = [
            {
                title: '序号',
                key: 'index',
                fixed: 'left',
                width: 80,
                render: (text, record, index) => index + 1,
            },
            {
                title: '商品名称',
                fixed: 'left',
                width: 220,
                dataIndex: 'proname',
                key: 'proname',
                // eslint-disable-next-line
                render: (text, record) => <a>{text}</a>
            },
            {
                title: '商品介绍',
                fixed: 'left',
                width: 220,
                dataIndex: 'desc',
                key: 'desc',
                render: (text, record) => record.desc
            },
            {
                title: <Tooltip title="点击右面漏斗进行筛选">商品分类</Tooltip>,
                width: 120,
                dataIndex: 'category',
                key: 'category',
            },
            {
                title: <Tooltip title="点击右面漏斗进行筛选">商品品牌</Tooltip>,
                width: 120,
                dataIndex: 'brand',
                key: 'brand',
            },
            {
                title: '商品图片',
                width: 120,
                dataIndex: 'swiper',
                key: 'swiper',
                render: (value) => <Image key="img" src={value[0]} width={100} height={100} placeholder={
                    <Image
                        preview={false}
                        src="https://web.chengqige.com/vipshop/v1/dist/static/loading.gif"
                        width={100}
                        height={100}
                    />
                }/>
            },
            {
                title: '商品原价',
                width: 120,
                dataIndex: 'originprice',
                sorter: (a, b) => a.originprice - b.originprice,
                key: 'originprice'
            },
            {
                title: '商品折扣',
                width: 120,
                dataIndex: 'discount',
                sorter: (a, b) => a.discount - b.discount,
                key: 'discount'
            },
            {
                title: '商品库存',
                width: 150,
                dataIndex: 'stock',
                key: 'stock'
            },
            {
                title: '操作',
                key: 'action',
                width: 150,
                fixed: 'right',
                render: (text, record, index) => (
                    <Space size="middle" key="action">
                        <Button size={'small'} onClick={this.edit.bind(this, record.proname)}>
                            编辑
                        </Button>
                        <Button size={'small'} onClick={this.remove.bind(this,record)} danger>
                            移除
                        </Button>
                    </Space>)
            }
        ]

        const empty = () => {
            return (<Empty
                description={
                    <span>上传队列为空</span>
                }/>)
        }

        console.log('render', this.state.dataSource)

        const element = <div style={{ height: this.state.tableHeight }}>
            <Space style={{ width: '100%' }} direction="vertical">
                <Space style={{ width: '100%' }}>
                    <Button onClick={this.addShopList.bind(this)}>添加商品</Button>
                    <Button onClick={this.importExcel.bind(this)}>从Excel导入</Button>
                    <Button type="primary" onClick={this.uploadShopList.bind(this)}>上传商品</Button>
                </Space>
                <ConfigProvider renderEmpty={empty}>
                    <Table style={{ width: '100%', position: 'relative' }} dataSource={this.state.dataSource}
                           columns={columns}
                           scroll={{ x: 1000, y: this.state.tableHeight }} rowKey={record => record.proname}/>
                </ConfigProvider>
            </Space>
            <Drawer className="EditModel" visible={this.state.editVisible} width={500}
                    title={this.state.edit ? '修改商品' : '添加商品'}
                    onClose={this.handerEditVisible.bind(this)} footer={null}>
                {this.state.edit ? <AddShop cb={this.modifyRow.bind(this)} edit={true} show={true}
                                            initData={this.state.editRow} proid="null" proname={true}/> : <AddShop
                    cb={this.appendRow.bind(this)}/>}
            </Drawer>
        </div>

        return <QueueAnim className="demo-content" key="demo">
            {this.props.show ? <div className="demo-tbody" key="a">{element}</div> : null}
        </QueueAnim>
    }
}

export default connect((state) => {
    return {
        show: state.getIn(['fade', 'show'])
    }
})(AddQuit)
